package com.felhr.serialportexample.ui;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.hardware.usb.UsbDevice;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.felhr.serialportexample.R;
import com.felhr.serialportexample.service.UsbWeighService;
import com.felhr.serialportexample.utils.DataUtils;

import java.lang.ref.WeakReference;
import java.util.Set;

public class WebActivity extends AppCompatActivity {

    SharedPreferences sp;

    private UsbWeighService usbService;
    private MyHandler mHandler;
    private WebView webView;
    private LinearLayout llTitle;
    private EditText etURL;
    private MyJavascriptInterface myJavascriptInterface=new MyJavascriptInterface();
    private static final String defUrl  = "http://192.168.150.39:7778/weight.html";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        sp = getApplication().getSharedPreferences("FILE_NAME", Context.MODE_PRIVATE);
        setContentView(R.layout.activity_web);
        initView();
        initWB();
        mHandler = new MyHandler(this);
        initLintener();
    }

    private void initView(){
        llTitle = findViewById(R.id.llTitle);
        etURL =findViewById(R.id.etURL);
    }

    @SuppressLint("JavascriptInterface")
    private void initWB(){
        webView = findViewById(R.id.wb);
        //声明WebSettings子类
        WebSettings webSettings = webView.getSettings();
        //如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        webSettings.setJavaScriptEnabled(true);
        //设置自适应屏幕，两者合用
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        //缩放操作
        webSettings.setSupportZoom(true); //支持缩放，默认为true。是下面那个的前提。
        webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false，则该WebView不可缩放
        webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件
        //其他细节操作
        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //关闭webview中缓存
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
        webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式
        webView.addJavascriptInterface(myJavascriptInterface,"MyJavascriptInterface");
        webView.loadUrl(getUrl());
        etURL.setText(webView.getUrl());
    }

    private void initLintener(){
        webView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                llTitle.setVisibility(llTitle.getVisibility()==View.VISIBLE?View.GONE:View.VISIBLE);
                return false;
            }
        });
        findViewById(R.id.tvSure).setOnClickListener(v -> {
//            showWeightToJS("90");
//            showToastToJS("90");
            webView.loadUrl(etURL.getText().toString());
            saveUrl(webView.getUrl());
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        setFilters();
        startService(UsbWeighService.class, usbConnection, null);
    }

    @Override
    public void onPause() {
        super.onPause();
        unregisterReceiver(mUsbReceiver);
        unbindService(usbConnection);
    }

    @Override
    protected void onDestroy() {
        if (mHandler != null) mHandler.removeCallbacks(null);
        super.onDestroy();
    }

    /**
     * sp 存储 url
     * @param url
     */
    private void saveUrl(String url){
         sp.edit().putString("url",url).commit();
    }

    /*
     * sp 获取 url
     */
    private String getUrl(){
        return sp.getString("url",defUrl);
    }

    private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (TextUtils.isEmpty(action)) return;
            switch (action) {
                case UsbWeighService.ACTION_USB_PERMISSION_GRANTED: // USB PERMISSION GRANTED
                    Toast.makeText(context, "USB Ready", Toast.LENGTH_SHORT).show();
                    break;
                case UsbWeighService.ACTION_USB_PERMISSION_NOT_GRANTED: // USB PERMISSION NOT GRANTED
                    Toast.makeText(context, "USB Permission not granted", Toast.LENGTH_SHORT).show();
                    break;
                case UsbWeighService.ACTION_NO_USB: // NO USB CONNECTED
                    Toast.makeText(context, "No USB connected", Toast.LENGTH_SHORT).show();
                    break;
                case UsbWeighService.ACTION_USB_DISCONNECTED: // USB DISCONNECTED
                    Toast.makeText(context, "USB disconnected", Toast.LENGTH_SHORT).show();
                    break;
                case UsbWeighService.ACTION_USB_NOT_SUPPORTED: // USB NOT SUPPORTED
                    Toast.makeText(context, "USB device not supported", Toast.LENGTH_SHORT).show();
                    break;
                case UsbWeighService.ACTION_PRINT:
                    UsbDevice usbDevice = intent.getParcelableExtra("device");
                    boolean isSupported = intent.getBooleanExtra("isSupported", false);
//                    tvSerialPort.append(usbDevice.toString() + "\n" + "isSupported: " + isSupported + "\n" + "设备名称: " + usbDevice.getDeviceName() + "\n");
                    break;
            }
        }
    };

    private final ServiceConnection usbConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName arg0, IBinder arg1) {
            usbService = ((UsbWeighService.UsbBinder) arg1).getService();
            usbService.setHandler(mHandler);
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            usbService = null;
        }
    };

    private void startService(Class<?> service, ServiceConnection serviceConnection, Bundle extras) {
        if (!UsbWeighService.SERVICE_CONNECTED) {
            Intent startService = new Intent(this, service);
            if (extras != null && !extras.isEmpty()) {
                Set<String> keys = extras.keySet();
                for (String key : keys) {
                    String extra = extras.getString(key);
                    startService.putExtra(key, extra);
                }
            }
            startService(startService);
        }
        Intent bindingIntent = new Intent(this, service);
        bindService(bindingIntent, serviceConnection, Context.BIND_AUTO_CREATE);
    }

    private void setFilters() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(UsbWeighService.ACTION_USB_PERMISSION_GRANTED);
        filter.addAction(UsbWeighService.ACTION_NO_USB);
        filter.addAction(UsbWeighService.ACTION_USB_DISCONNECTED);
        filter.addAction(UsbWeighService.ACTION_USB_NOT_SUPPORTED);
        filter.addAction(UsbWeighService.ACTION_USB_PERMISSION_NOT_GRANTED);
        filter.addAction(UsbWeighService.ACTION_PRINT);
        registerReceiver(mUsbReceiver, filter);
    }

    private static class MyHandler extends Handler {
        private final WeakReference<WebActivity> mWeakReference;

        public MyHandler(WebActivity activity) {
            mWeakReference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            WebActivity mActivity = mWeakReference.get();
            if (mActivity == null || mActivity.isFinishing()) return;
            switch (msg.what) {
                case UsbWeighService.MESSAGE_FROM_SERIAL_PORT:
                    String data = (String) msg.obj;
//                    mActivity.tvInfo.setText(DataUtils.pareData(data));//显示重量
//                    mActivity.tvDisplay.append(data);//显示重量
                    mActivity.showWeightToJS(DataUtils.pareDataNoUnit(data));
                    break;
                case UsbWeighService.CTS_CHANGE:
                    Toast.makeText(mActivity, "CTS_CHANGE", Toast.LENGTH_LONG).show();
                    break;
                case UsbWeighService.DSR_CHANGE:
                    Toast.makeText(mActivity, "DSR_CHANGE", Toast.LENGTH_LONG).show();
                    break;
            }
        }
    }

    public void showWeightToJS(String weight){
        webView.loadUrl("javascript:showWeight("+weight+")");
    }

    public void showToastToJS(String str){
        webView.loadUrl("javascript:showToast("+90+")");
    }

    public class MyJavascriptInterface {
        //归零
        @JavascriptInterface
        public void jsoOrderZero(){
            //归零
            if (usbService != null) {
                usbService.write(orderZero());
            }
        }
        //去皮
        @JavascriptInterface
        public void jsoOrderRemovePeel(){
            //去皮
            if (usbService != null) {
                usbService.write(orderRemovePeel());
            }
        }
    }

    /**
     * 将秤盘上的重量置为零重基准
     */
    byte[] orderZero() {
        byte[] orderZero = new byte[7];
        orderZero[0] = 0X01;
        orderZero[1] = 0X22;
        orderZero[2] = 0X00;
        orderZero[3] = 0X00;
        orderZero[4] = 0X00;
        orderZero[5] = 0X00;
        orderZero[6] = 0X23;
        return orderZero;
    }

    /**
     * 将秤盘上的重量置为皮重
     */
    byte[] orderRemovePeel() {
        byte[] orderZero = new byte[7];
        orderZero[0] = 0X01;
        orderZero[1] = 0X23;
        orderZero[2] = 0X00;
        orderZero[3] = 0X00;
        orderZero[4] = 0X00;
        orderZero[5] = 0X00;
        orderZero[6] = 0X22;
        return orderZero;
    }

    /**
     * 零点校准
     */
    byte[] onZeroCalibration() {
        byte[] orderZero = new byte[7];
        orderZero[0] = 0X01;
        orderZero[1] = 0X26;
        orderZero[2] = 0X00;
        orderZero[3] = 0X00;
        orderZero[4] = 0X00;
        orderZero[5] = 0X00;
        orderZero[6] = 0X27;
        return orderZero;
    }

    /**
     * 最大称重
     */
    byte[] onMaxweighing() {
        byte[] orderZero = new byte[7];
        orderZero[0] = 0X01;
        orderZero[1] = 0X25;
        orderZero[2] = 0X30;
        orderZero[3] = 0X75;
        orderZero[4] = 0X00;
        orderZero[5] = 0X00;
        orderZero[6] = 0X61;
        return orderZero;
    }
}